import { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Block from '@/custom/Block';
import {
  Card,
  Form,
  Button,
  Table,
  Divider,
  Input,
  Select,
  Modal,
  message,
  Popconfirm,
  Checkbox
} from 'antd'; // 引入antd组件
import UnipicUpload from '@/custom/UnipicUpload';
import AntdspConfig from '@/AntdspConfig'

const FormItem = Form.Item;

const UserStatus = {
  NORMAL: '正常',
  FORBIDDEN: '异常',
};

@connect(({ systempermission, loading }) => ({
  systempermission,
  loading: loading.models.systempermission,
}))
/**
 * PureComponent的子组件一般由3大部分构成：数据、事件、render()渲染
 */
@Form.create()// 创建表单，antd语法
export default class extends PureComponent {
  state = {
    confirmLoading: false,
    visible: false,
    current: {},
    formValue: {
      page: 1,
      count: 10,
    },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systempermission/fetchAll',
      payload: {
        page: 1,
        count: 10,
      },
    });
  }

  // 条件查询事件
  handlerQueryOnClick = () => {
    const { form, dispatch } = this.props; // 从this.props取出form、dispatch
    form.validateFields((err, fieldsValue) => {
      let { formValue } = this.state.formValue;
      formValue = {
        ...fieldsValue,
        page: 1,
        count: 10,
      };
      this.setState({ formValue });// 更新state的formValue
      // 调用user.js里面的*fetchAll
      dispatch({
        type: 'systempermission/fetchAll',
        payload: {
          ...formValue,
        },
      });
    });
  };

  renderQueryForm = () => {
    const { getFieldDecorator } = this.props.form;

    return (
      <Block>
        <Form layout="inline">
          <FormItem label="登录名">
            {getFieldDecorator('loginname')(<Input placeholder={'请输入登录名'} />)}
          </FormItem>
          <FormItem label="状态">
            {getFieldDecorator('status')(
              <Select style={{ width: '120px' }} placeholder="请选择状态">
                <Select.Option value={'NORMAL'}>正常</Select.Option>
                <Select.Option value={'FORBIDDEN'}>异常</Select.Option>
              </Select>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={this.handlerQueryOnClick}>
              查询
            </Button>
          </FormItem>
        </Form>
      </Block>
    );
  };

  handlerTableOnChange = (pagination, filters, sorter) => {
    const { dispatch } = this.props;
    let { formValue } = this.state;

    formValue = {
      ...formValue,
      page: pagination.current,
      count: pagination.pageSize,
    };

    this.setState({
      formValue: {
        ...formValue,
      },
    });

    dispatch({
      type: 'systempermission/fetchAll',
      payload: {
        ...formValue,
      },
    });
  };
  // 显示弹窗
  handlerModalOnOk = e => {
    e.preventDefault();
  };

  // 删除事件

  // 渲染列表。数据、columns定义、return里面写html
  render() {
    const {
      systempermission: { PermissionList, detail },  // 命名空间：{ 对象1, 对象2, ......}
      loading,
    } = this.props;// 从user.js取出数据

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '描述',
        dataIndex: 'desc',
      },
      {
        title: '创建时间',
        dataIndex: 'created',
      }
    ];

    return (
      <PageHeaderWrapper title="用户管理">
        <Card>
          {this.renderQueryForm()}

          <Block>
            <Button
              icon="plus"
              type="primary"
              onClick={(e) => {
                this.showModal(e , {});
              }}
            >
              新增
            </Button>
          </Block>
          <Table
            columns={columns}
            rowKey={'id'}
            dataSource={PermissionList.data}
            pagination={PermissionList.pagination}
            onChange={this.handlerTableOnChange}
            loading={loading}
          />
          <Modal
            title="编辑用户信息"
            centered={true}
            maskClosable={true}
            visible={this.state.visible}
            onCancel={() => {
              this.setState({ visible: false });
            }}
            onOk={this.handlerModalOnOk}
            confirmLoading={this.state.confirmLoading}
            destroyOnClose={true}
          >
            <EditUser
              wrappedComponentRef={formRef => (this.formRef = formRef)}
              detail={detail}
            />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

@Form.create() // 弹窗组件
export class EditUser extends PureComponent {
  // 比对密码事件
  compareToPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入不一致');
    } else {
      callback();
    }
  };

  handlerUploadOnChange=(imageurl)=>{
    console.log(imageurl);
    this.setState({
      avatar: imageurl
    })
  }

  roleToNameId(roleNameId){

    let newRoleNameId=[];

    roleNameId.map((item=>{
      let nameid = {
        label: item.roleName,
        value: item.id,
      }
      newRoleNameId.push(nameid);
    }));
    return newRoleNameId;
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { detail: { user , roleIds , roles} } = this.props;

    const flag = Object.keys(user).length == 0;

    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 },
      },
    };

    return (
      <div>
        <Form layout="horizontal" {...formItemLayout}>
          <FormItem label="头像">
            {getFieldDecorator('avatar',{
              initialValue: user.avatar
            })(
              <UnipicUpload
                group={"user"}
                onChange={()=>{this.handlerUploadOnChange}}
                image={user.avatar}
              />
            )}
          </FormItem>
          <FormItem label="登录名">
            {getFieldDecorator('loginname', {
              initialValue: user.loginname,
              rules: [
                {
                  required: true,
                  message: '请输入登录名',
                },
              ],
            })(<Input placeholder="将会成为您唯一的登入名" disabled={!flag} />)}
          </FormItem>
          {flag ? (
            <div>
              <FormItem label="密 码">
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                  ],
                })(<Input.Password placeholder="请输入密码" />)}
              </FormItem>
              <FormItem label="确认密码">
                {getFieldDecorator('repassword', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      validator: this.compareToPassword,
                    },
                  ],
                })(<Input.Password placeholder="确认密码" />)}
              </FormItem>
            </div>
          ) : null}
          <FormItem label="真实姓名">
            {getFieldDecorator('realname', {
              initialValue: user.realname,
            })(<Input placeholder="真实姓名" />)}
          </FormItem>
          <FormItem label="Email">
            {getFieldDecorator('email', {
              initialValue: user.email,
            })(<Input placeholder="email" />)}
          </FormItem>
          <FormItem label="Q  Q">
            {getFieldDecorator('qq', {
              initialValue: user.qq,
            })(<Input placeholder="qq" />)}
          </FormItem>
          <FormItem label="选择角色">
            {
              getFieldDecorator('roleIds',{
                initialValue: flag ? [] : roleIds
              })(
                <Checkbox.Group options={this.roleToNameId(roles)} ></Checkbox.Group>
              )
            }
          </FormItem>
        </Form>
      </div>
    );
  }
}
